package com.cindata

import grails.gorm.transactions.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Secured(['isAuthenticated()'])
@Transactional
class WorkflowUserController {

    def springSecurityService

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def index(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        respond WorkflowUser.list(params), model:[workflowUserCount: WorkflowUser.count()]
    }

    def show(WorkflowUser workflowUser) {
        respond workflowUser
    }

    def create() 
    {
        params['targetUri'] = request.getHeader("referer")
        respond new WorkflowUser(params)
    }

    @Transactional
    def save(WorkflowUser workflowUser)
    {
        if (workflowUser == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (workflowUser.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond workflowUser.errors, view:'create'
            return
        }

        workflowUser.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'workflowUser.label', default: 'workflowUser'), workflowUser.id])
                redirect url: params['targetUri']
            }
            '*' { respond workflowUser, [status: CREATED] }
        }
    }

    def edit(WorkflowUser workflowUser)
    {
        params['targetUri'] = request.getHeader("referer")
        respond workflowUser
    }

    @Transactional
    def update(WorkflowUser workflowUser) {
        if (workflowUser == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (workflowUser.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond workflowUser.errors, view:'edit'
            return
        }

        workflowUser.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'workflowUser.label', default: 'workflowUser'), workflowUser.id])
                redirect url: params['targetUri']
            }
            '*'{ respond workflowUser, [status: OK] }
        }
    }

    @Transactional
    def delete(WorkflowUser workflowUser)
    {
        def targetUri = request.getHeader("referer")

        if (workflowUser == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        workflowUser.delete flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'workflowUser.label', default: 'workflowUser'), workflowUser.id])
                redirect url: targetUri
            }
            '*'{ render status: NO_CONTENT }
        }
    }

    protected void notFound() {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'workflowUser.label', default: 'workflowUser'), params.id])
                redirect action: "index", method: "GET"
            }
            '*'{ render status: NOT_FOUND }
        }
    }

    // 押品待办
    def collateralPending()
    {

        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0

        def externalId = params["externalId"]

        def estateQueryParam = new HashMap()
        def sql = " "

        if (externalId && externalId != "") {
            sql += " and stage.instance.collateral.externalId like :externalId "
            estateQueryParam['externalId'] = '%' + externalId + '%'
        }
        def user = User.findByUsername(springSecurityService.getPrincipal().username)
        def status = params['status']

        def  tempSql

        if (!status) {
            tempSql = "select stage.instance.collateral.id, stage.instance.collateral.externalId, stage.instance.name, stage.instance.stage.name, stage.instance.status.name, stage.instance.createdDate, stage.instance.modifiedDate, stage.id from WorkflowInstanceUser where user.id = ${user?.id} and stage.id = stage.instance.stage.id and stage.instance.status.name = 'Pending' "
            tempSql+=sql
        } else if (status == 'Already') {
            tempSql = "select stage.instance.collateral.id, stage.instance.collateral.externalId, stage.instance.name, stage.instance.stage.name, stage.instance.status.name, stage.instance.createdDate, stage.instance.modifiedDate, stage.id from WorkflowInstanceUser where user.id = ${user?.id} and stage.executionSequence < stage.instance.stage.executionSequence group by stage.instance.name "
        }
        tempSql+=" order by stage.instance.collateral.modifiedDate desc"


        def workflowInstanceUserList = WorkflowInstanceUser.executeQuery(tempSql, estateQueryParam,[max: max, offset: offset])
        def list = WorkflowInstanceUser.executeQuery(tempSql,estateQueryParam)
        def count = list?.size()
        respond workflowInstanceUserList, model: [workflowInstanceUserList: workflowInstanceUserList, workflowInstanceUserCount: count], view: 'collateralPending'
    }

    // 预警待办
    def riskWarningPending()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0

        def user = User.findByUsername(springSecurityService.getPrincipal().username)
        def status = params['status']
        def sql
        if (!status)
        {
            sql = "select stage.instance.riskWarning.id, stage.instance.riskWarning.externalId, stage.instance.name, stage.instance.stage.name, stage.instance.status.name, stage.instance.createdDate, stage.instance.modifiedDate, stage.id from WorkflowInstanceUser where user.id = ${user?.id} and stage.id = stage.instance.stage.id and stage.instance.status.name = 'Pending' order by stage.instance.riskWarning.modifiedDate desc"
        }
        else if (status == 'Already')
        {
            sql = "select stage.instance.riskWarning.id, stage.instance.riskWarning.externalId, stage.instance.name, stage.instance.stage.name, stage.instance.status.name, stage.instance.createdDate, stage.instance.modifiedDate, stage.id from WorkflowInstanceUser where user.id = ${user?.id} and stage.executionSequence < stage.instance.stage.executionSequence group by stage.instance.name order by stage.instance.riskWarning.modifiedDate desc"
        }
        def workflowInstanceUserList = WorkflowInstanceUser.executeQuery(sql, [max: max, offset: offset])
        def list = WorkflowInstanceUser.executeQuery(sql)
        def count = list?.size()

        respond workflowInstanceUserList, model: [workflowInstanceUserList: workflowInstanceUserList, workflowInstanceUserCount: count]
    }

    // 不良资产包待办
    def abnormalMortgageBatchPending()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0

        def user = User.findByUsername(springSecurityService.getPrincipal().username)
        def status = params['status']
        def sql
        if (!status)
        {
            sql = "select stage.instance.abnormalMortgageBatch.id, stage.instance.abnormalMortgageBatch.externalId, stage.instance.name, stage.instance.stage.name, stage.instance.status.name, stage.instance.createdDate, stage.instance.modifiedDate, stage.id from WorkflowInstanceUser where user.id = ${user?.id} and stage.id = stage.instance.stage.id and stage.instance.status.name = 'Pending' order by stage.instance.abnormalMortgageBatch.modifiedDate desc"
        }
        else if (status == 'Already')
        {
            sql = "select stage.instance.abnormalMortgageBatch.id, stage.instance.abnormalMortgageBatch.externalId, stage.instance.name, stage.instance.stage.name, stage.instance.status.name, stage.instance.createdDate, stage.instance.modifiedDate, stage.id from WorkflowInstanceUser where user.id = ${user?.id} and stage.executionSequence < stage.instance.stage.executionSequence group by stage.instance.name order by stage.instance.abnormalMortgageBatch.modifiedDate desc"
        }
        def workflowInstanceUserList = WorkflowInstanceUser.executeQuery(sql, [max: max, offset: offset])
        def list = WorkflowInstanceUser.executeQuery(sql)
        def count = list?.size()

        respond workflowInstanceUserList, model: [workflowInstanceUserList: workflowInstanceUserList, workflowInstanceUserCount: count]
    }

    // 机构待办
    def accountPending()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0

        def user = User.findByUsername(springSecurityService.getPrincipal().username)
        def status = params['status']
        def sql
        if (!status)
        {
            sql = "select stage.instance.account.id, stage.instance.account.externalId, stage.instance.name, stage.instance.stage.name, stage.instance.status.name, stage.instance.createdDate, stage.instance.modifiedDate, stage.id from WorkflowInstanceUser where user.id = ${user?.id} and stage.id = stage.instance.stage.id and stage.instance.status.name = 'Pending' order by stage.instance.account.modifiedDate desc"
        }
        else if (status == 'Already')
        {
            sql = "select stage.instance.account.id, stage.instance.account.externalId, stage.instance.name, stage.instance.stage.name, stage.instance.status.name, stage.instance.createdDate, stage.instance.modifiedDate, stage.id from WorkflowInstanceUser where user.id = ${user?.id} and stage.executionSequence < stage.instance.stage.executionSequence group by stage.instance.name order by stage.instance.account.modifiedDate desc"
        }
        def workflowInstanceUserList = WorkflowInstanceUser.executeQuery(sql, [max: max, offset: offset])
        def list = WorkflowInstanceUser.executeQuery(sql)
        def count = list?.size()

        respond workflowInstanceUserList, model: [workflowInstanceUserList: workflowInstanceUserList, workflowInstanceUserCount: count]
    }
}
